package com.liam.lotterysystem.controller;

import com.liam.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.liam.lotterysystem.common.exception.ControllerException;
import com.liam.lotterysystem.common.pojo.CommonResult;
import com.liam.lotterysystem.common.utils.JacksonUtil;
import com.liam.lotterysystem.controller.param.ShortMessageLoginParam;
import com.liam.lotterysystem.controller.param.UserLoginParam;
import com.liam.lotterysystem.controller.param.UserPasswordLoginParam;
import com.liam.lotterysystem.controller.param.UserRegisterParam;
import com.liam.lotterysystem.controller.result.BaseUserInfoResult;
import com.liam.lotterysystem.controller.result.UserLoginResult;
import com.liam.lotterysystem.controller.result.UserRegisterResult;
import com.liam.lotterysystem.service.UserService;
import com.liam.lotterysystem.service.VerificationCodeService;
import com.liam.lotterysystem.service.dto.UserDTO;
import com.liam.lotterysystem.service.dto.UserLoginDTO;
import com.liam.lotterysystem.service.dto.UserRegisterDTO;
import com.liam.lotterysystem.service.enums.UserIdentityEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: LiamLMK
 * @CreateTime: 2024-10-11
 * @Description:
 * @Version: 1.0
 */

//@Slf4j
@Tag(name = "用户功能")
@RestController
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private VerificationCodeService verificationCodeService;


    /**
     * 用户注册
     *
     * @param param
     * @return
     */
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(
            @Validated @RequestBody UserRegisterParam param) {
        // 日志打印
        log.info("userRegister UserRegisterParam:{}", JacksonUtil.writeValueAsString(param));
        // 调用Service 进行服务访问
        UserRegisterDTO userRegisterDTO = userService.register(param);
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));

    }

    /**
     * 发送验证码
     *
     * @param phoneNumber
     * @return
     */
    @Operation(summary = "发送验证码")
    @GetMapping("verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(@Parameter(description = "电话号码") @RequestParam("phoneNumber") String phoneNumber) {
        log.info("sendVerificationCode phoneNumber:{}", phoneNumber);
        verificationCodeService.sendVerificationCode(phoneNumber);
        return CommonResult.success(Boolean.TRUE);

    }

    /**
     * 密码登录
     *
     * @param param
     * @return
     * @RequestBody 前端传来JSON字符串 后端直接转换成对象param
     */
    @Operation(summary = "密码登录")
    @PostMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(
            @Validated @RequestBody
            UserPasswordLoginParam param) {

        log.info("userPasswordLogin UserPasswordLoginParam: {}", param);
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        if (userLoginDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        UserLoginResult result = new UserLoginResult();
        result.setToken(userLoginDTO.getToken());
        result.setIdentity(userLoginDTO.getIdentity().name());

        return result;

    }

    /**
     * 短信验证码登录
     *
     * @param param
     * @return
     */
    @Operation(summary = "验证码登录")
    @PostMapping("/message/login")
    public CommonResult<UserLoginResult> shortMessageLogin(
            @Validated @RequestBody
            ShortMessageLoginParam param) {

        log.info("shortMessageLogin ShortMessageLoginParam: {}", param);
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }
    // bug报告2: 两个@PostMapping注解的映射地址是一样的，都是“/password/login”, 引起模糊映射

    /**
     * 查找用户信息
     * @param identity
     * @return
     */
    @Operation(summary = "查找用户信息")
    @GetMapping("/base-user/find-list")
    public CommonResult<List<BaseUserInfoResult>> findBaseUserInfo(String identity) {
        log.info("findBaseUserInfo identity: {}", identity);
        List<UserDTO> userDTOList = userService.findUserInfo(
                UserIdentityEnum.forName(identity));
        return CommonResult.success(convertToList(userDTOList));
    }

    private List<BaseUserInfoResult> convertToList(List<UserDTO> userDTOList) {
        if (CollectionUtils.isEmpty(userDTOList)) {
            return Arrays.asList();
        }
        return userDTOList.stream()
                .map(userDTO -> {
                    BaseUserInfoResult result = new BaseUserInfoResult();
                    result.setUserId(userDTO.getUserId());
                    result.setUserName(userDTO.getUserName());
                    result.setIdentity(userDTO.getIdentity().name());
                    return result;
                }).collect(Collectors.toList());
    }

    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {

        UserRegisterResult result = new UserRegisterResult();
        if (userRegisterDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }

        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }
}
